package com.svmc.app.task.activity;

import java.util.ArrayList;
import java.util.Calendar;

import luyenlv.pro.screen.base.BaseActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.svmc.app.task.adapter.DbAdapter;
import com.svmc.app.task.adapter.ListAdapter;
import com.svmc.app.task.adapter.ListAllTaskAdapter;
import com.svmc.app.task.alarm.MyAlarmManager;
import com.svmc.app.task.controller.SwipeListViewTouchListener;
import com.svmc.app.task.model.ActionItem;
import com.svmc.app.task.model.ActionItemOption;
import com.svmc.app.task.model.TaskModel;
import com.svmc.app.task.tabmanager.TabGroupActivity;
import com.svmc.app.task.tabmanager.TabMain;
import com.svmc.app.task.utils.CommonDefine;
import com.svmc.app.task.utils.ConfigModel;
import com.svmc.app.task.utils.DateUtils;
import com.svmc.app.task.view.CustomDialog;
import com.svmc.app.task.view.DialogConfirm;
import com.svmc.app.task.view.QuickAction;
import com.svmc.app.task.view.QuickActionOption;
import com.svmc.app.task.view.QuickActionOption.OnActionItemClickListener;
import com.svmc.app.task.view.QuickActionOption.OnDismissListener;

public class TaskActivity extends BaseActivity implements OnClickListener,
		CommonDefine {
	// private final static int DIALOG_INFO = 1;
	ArrayList<TaskModel> listtask;
	Calendar c = Calendar.getInstance();
	ListView ls;
	//ListView drapdropList;
	DateUtils dateUtils = new DateUtils();
	TabGroupActivity parentActivity;
	ImageView optionMenu,search_icon;
	int isfocusview = 0;
	RelativeLayout main_land;
	EditText search_edt;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		View viewToLoad = LayoutInflater.from(this.getParent()).inflate(getLayout(R.array.main_layout), null);
//		setContentView(viewToLoad);
		setContentView(getLayout(R.array.main_layout));
		
		findViewById(R.id.main_img_alltask).setOnClickListener(this);
		findViewById(R.id.main_img_addnew).setOnClickListener(this);
		search_icon=(ImageView) findViewById(R.id.main_img_search);
		search_icon.setOnClickListener(this);
		findViewById(R.id.main_img_sort).setOnClickListener(this);
		optionMenu = (ImageView)findViewById(R.id.main_img_sort);
		search_edt = (EditText)findViewById(R.id.main_edt_search);
		search_edt.setVisibility(View.GONE);
		ls = (ListView) findViewById(R.id.main_ls);
		parentActivity = (TabGroupActivity)getParent();
		SharedPreferences mPreferences =PreferenceManager.getDefaultSharedPreferences(this);
		boolean firstTime = mPreferences.getBoolean("firstTime_app", true);
		if (firstTime) { 
			 SharedPreferences.Editor editor = mPreferences.edit();
			 editor.putBoolean("firstTime_app", false);
			 editor.putString(DELETE_SCHEDULE_TYPE_SETTING,VALUE_SETTING_SCHEDULE_DELETE_OFF);
			 editor.putString(ALARM_FREQUENCY_TYPE_SETTING,VALUE_SETTING_ALARM_FREQUENCY_OFF);
			 editor.putString(DATE_FORMAT_TYPE, VALUE_SETTING_DATE_FORMAT_1);
			 editor.putString(TIME_FORMAT_TYPE, VALUE_SETTING_TIME_FORMAT_1);
			 editor.putBoolean(SHARE_ONLINE_TYPE, true);
			 editor.putBoolean(SYNCHRONIZE_TYPE, false);
			 editor.commit();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//showToast("onresume TaskActivity"+TabGroupActivity.stateActivity, 0);
		if(TabGroupActivity.stateActivity==ADD_NEW_ACTIVITY){
			Intent restoreAddNewActivity = new Intent(this, AddNewTask.class);
			parentActivity.replaceContentView("Addnewtask", restoreAddNewActivity);
			TabGroupActivity.stateActivity=0;
		}else if (TabGroupActivity.stateActivity==EDIT_ACTIVITY) {			
			Intent restoreEditActivity = new Intent(this, EditTask.class);
			restoreEditActivity.putExtra("id_task", TabGroupActivity.id_data);
			parentActivity.replaceContentView("EditTask", restoreEditActivity);
			TabGroupActivity.stateActivity=0;
		}else {
			//showToast("else nothing", 0);
			updateAllTask();
			TabGroupActivity.stateActivity=0;
		}
		
		//updateAllTask();
		//updateListTaskNotFinish();
		
	}


	public void onClick(View v) {
		// MyAlarmManager alarmManager = new MyAlarmManager(this);
		// DateUtils date = new DateUtils();
		// CalenderModel cal = new CalenderModel();
		switch (v.getId()) {
		case R.id.main_img_alltask:			
			//getAllTaskToShow();
			
			updateListTaskNotFinish();
			break;
		case R.id.main_img_addnew:
			Intent addnewIntent = new Intent(this, AddNewTask.class);
//			TabGroupActivity parentActivity = (TabGroupActivity)getParent();
			parentActivity.startChildActivity("Addnewtask", addnewIntent);
			
//			startActivity(addnewIntent);

			break;
		case R.id.main_img_search:
			// sortNameAllTask("DESC");
			search_edt.setVisibility(View.VISIBLE);
			search_edt.requestFocus();
			showKeybroad(search_edt);
			searchData();
			break;
		case R.id.main_img_sort:
			//sortNameAllTask("DESC");
			// updateAllTask();
			showOptionMenu(optionMenu);
			break;
		default:
			break;
		}

	}
	public void searchData (){
		search_edt.addTextChangedListener(new TextWatcher() {
			ArrayList<TaskModel> resultSearch = new ArrayList<TaskModel>();
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				resultSearch.clear();
				String searchString	= search_edt.getText().toString();
				int searchlenght = searchString.length();
				int sizeListstask = listtask.size();
				for (int i=0;i<sizeListstask;i++){
					String nameTask = listtask.get(i).getTask().toString();
					if(searchlenght <= nameTask.length()){
						if(searchString.equalsIgnoreCase(nameTask.substring(0, searchlenght))){
							resultSearch.add(listtask.get(i));
						}
					}
					ListAllTaskAdapter myadapter = new ListAllTaskAdapter(TaskActivity.this, resultSearch);
					ls.setAdapter(myadapter);
					myadapter.notifyDataSetChanged();
					if(resultSearch.size()==0){
						hideListView();
					}else {
						showListView();
					}
					if(searchlenght==0){
						ListAllTaskAdapter adapter = new ListAllTaskAdapter(TaskActivity.this, listtask);
						ls.setAdapter(adapter);
					}
				}
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				
				
			}
		});
		
		
	}

	/**
	 * Showtoast is customed by anhson
	 * 
	 * @param text
	 * @param type
	 */

	public void showToast(String text, int type) {
		Toast.makeText(this, text, type).show();
	}

	/**
	 * refresh listview
	 */

	public void updateListTaskNotFinish() {
		isfocusview = UPDATE_TASK_NOT_FINISH;
		DbAdapter db = new DbAdapter(TaskActivity.this);
		listtask = db.getAllTaskByStatus(0);
		if (listtask.size() != 0) {
			ls.setVisibility(View.VISIBLE);
			ListAdapter myadapter = new ListAdapter(this, listtask);
			ls.setAdapter(myadapter);			
			listenClickListView();
			if(ConfigModel.getApiLevel()>=11){
				//swipeListview();
			}
		} else {
			ls.setVisibility(View.GONE);
			showToast("Nothing", Toast.LENGTH_LONG);
		}

	}

	public void updateAllTask() {
		isfocusview=UPDATE_ALL_TASK;
		DbAdapter db = new DbAdapter(this);
		listtask = db.getAllTask();
		if (listtask.size() != 0) {
			ListAllTaskAdapter myadapter = new ListAllTaskAdapter(this, listtask);
			ls.setAdapter(myadapter);
			listenClickListView();
			
			// only android 3.0 and heigher.
			if(ConfigModel.getApiLevel()>=11){
				swipeListview();
			}
			
		} else {
//			showToast("Nothing", Toast.LENGTH_LONG);
			hideListView();
		}
	}

	public void sortNameAllTask(String type) {
		isfocusview = SORT_BY_NAME_TASK;
		DbAdapter db = new DbAdapter(TaskActivity.this);
		listtask = db.getAllTastSortName(type);
		if (listtask.size() != 0) {
			ListAllTaskAdapter myadapter = new ListAllTaskAdapter (this, listtask);
			ls.setAdapter(myadapter);
			myadapter.notifyDataSetChanged();
		} else {
			showToast("Nothing", Toast.LENGTH_LONG);
		}
	}
	public void sortAllTaskByTime(String type) {
		isfocusview = SORT_BY_TIME_FINISH_TASk;
		DbAdapter db = new DbAdapter(TaskActivity.this);
		listtask = db.getAllTaskSortTime(type);
		if (listtask.size() != 0) {
			ListAllTaskAdapter myadapter = new ListAllTaskAdapter(this, listtask);
			ls.setAdapter(myadapter);
			myadapter.notifyDataSetChanged();
		} else {
			
			showToast("Nothing", Toast.LENGTH_LONG);
		}
	}
	public void hideListView(){	
			ls.setVisibility(View.GONE);
	}
	public void showListView(){
		ls.setVisibility(View.VISIBLE);
	}

	public void deleteAll() {
		MyAlarmManager myalarm = new MyAlarmManager(this);
		myalarm.deleteAllAlarm();
		DbAdapter db = new DbAdapter(TaskActivity.this);	
		db.deteleAllTask();			
		hideListView();
		showToast("Delete all successful ", Toast.LENGTH_LONG);
		
	}
	
	public void deleteOneTask(TaskModel task){
		DbAdapter db = new DbAdapter(TaskActivity.this);
		listtask =db.getAllTask();
		int indexrow = db.deleteTaskByID(task.getId());
		if(indexrow>0){
			MyAlarmManager myalarm = new MyAlarmManager(this);
			myalarm.cancelAlarm(task.getId_alarm());
			switch (isfocusview) {
			case UPDATE_ALL_TASK:
				updateAllTask();
				break;
			case SORT_BY_TIME_FINISH_TASk:
				sortAllTaskByTime("ASC");
				break;
			case SORT_BY_NAME_TASK:
				sortNameAllTask("ASC");
				break;
			case UPDATE_TASK_NOT_FINISH:
				updateListTaskNotFinish();
				break;
			default:
				break;
			}
			
		}
	}

	@Override
	public void clearMemory() {
		unbindReferences(this, R.id.RelativeLayout1);

	}

	public void listenClickListView() {
		final CustomDialog mydialog = new CustomDialog(getDialogContext());
		ls.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {
				mydialog.setDialogType(DIALOG_INFO, listtask.get(position)
						.getTask(), listtask.get(position).getNote(), listtask
						.get(position).getTimefinish());
					mydialog.show();
				
				
			}

		});
		
		ls.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				showQuickAction(view, position);
				return true;
			}
		});
	}

	public void getAllTaskToShow() {
		DbAdapter db = new DbAdapter(TaskActivity.this);
		listtask = db.getAllTask();
		if (listtask.size() != 0) {
			ListAllTaskAdapter allAdapter = new ListAllTaskAdapter(this,
					listtask);
			ls.setAdapter(allAdapter);
		} else {
			showToast("Nothing", 0);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_CODE_EDIT_TASK:
			if (resultCode == RESULT_OK) {
				// todo something.
				updateListTaskNotFinish();
			}
			break;
		case REQUEST_CODE_DELETE_TASK:
			if(resultCode==RESULT_OK){
				updateListTaskNotFinish();
			}
			break;
		default:
			break;
		}

	}

	/**
	 * show quick action
	 */
	public void showQuickAction(View v, final int position) {
		
		// Add action item
		ActionItem addAction = new ActionItem();

		addAction.setTitle(getString(R.string.contextmenu_edit));
		addAction.setIcon(getResources().getDrawable(
				R.drawable.icon_edit_quickaction));

		// Accept action item
		ActionItem accAction = new ActionItem();

		accAction.setTitle(getString(R.string.contextmenu_delete));
		accAction.setIcon(getResources().getDrawable(
				R.drawable.icon_delete_quickaction));

		// Upload action item
		ActionItem upAction = new ActionItem();

		upAction.setTitle(getString(R.string.contextmenu_share));
		upAction.setIcon(getResources().getDrawable(
				R.drawable.icon_share_quickaction));

		final QuickAction mQuickAction = new QuickAction(this);

		mQuickAction.addActionItem(addAction);
		mQuickAction.addActionItem(accAction);
		mQuickAction.addActionItem(upAction);

		// setup the action item click listener
		mQuickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					Intent intent;

					@Override
					public void onItemClick(int pos) {

						if (pos == EDIT_OPTION) { // Add item selected
							// Toast.makeText(TaskActivity.this,
							// "Add item selected : " +position,
							// Toast.LENGTH_SHORT).show();
							intent = new Intent(TaskActivity.this,
									EditTask.class);
							intent.putExtra("id_task", listtask.get(position)
									.getId());
							// if(listtask.get(position).getPathRingtone()
							// !=null){
							// intent.putExtra("path_ring",
							// listtask.get(position).getPathRingtone());
							// }
//							startActivityForResult(intent,
//									REQUEST_CODE_EDIT_TASK);
//							TabGroupActivity parentActivity = (TabGroupActivity)getParent();
							parentActivity.startChildActivity("EditTask", intent);
						} else if (pos == DELETE_OPTION) { // Accept item
															// selected
//							CustomDialog mydialog = new CustomDialog(getDialogContext());
//							mydialog.setDialogType(DIALOG_CONFIRM_DELETE, getString(R.string.dialog_confirm_message), listtask.get(position));
//							mydialog.show();
							intent = new Intent(TaskActivity.this,
									DialogConfirm.class);
							intent.putExtra("id_task", listtask.get(position)
									.getId());
							intent.putExtra("id_alarm", listtask.get(position).getId_alarm());
							startActivity(intent);
							//TabGroupActivity parentActivity = (TabGroupActivity)getParent();
//							parentActivity.startChildActivity("DeleteTask", intent);
							
						} else if (pos == SHARE_OPTION) { 	
							CustomDialog mydialog = new CustomDialog(getDialogContext());
							if(getbooleanPreferences(SHARE_ONLINE_TYPE)==true){
								if (isNetworkOnline()==false) {
									mydialog.setDialogType(DIALOG_NOTIFY, getString(R.string.info_network_off));
									mydialog.show();
								}
								postToWall();	
							}else {
								
								mydialog.setDialogType(DIALOG_NOTIFY,getString(R.string.notify_use_funtion_shareonline));
								mydialog.show();
							}
																				
						}
					}
				});
		mQuickAction.show(v);
		mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
	}
	@SuppressWarnings("deprecation")
	public void postToWall() {
		Facebook facebook;
		facebook = new Facebook(APP_ID);
	    // post on user's wall.
	    facebook.dialog(getDialogContext(), "feed", new DialogListener() {
	 
	        @Override
	        public void onFacebookError(FacebookError e) {
	        }
	        
	        @Override
	        public void onError(DialogError e) {
	        }
	 
	        @Override
	        public void onComplete(Bundle values) {
	        	
	        	
	        }
	 
	        @Override
	        public void onCancel() {
	        }
	    });
	 
	}

	
	public void showOptionMenu (View v){
		
		ActionItemOption sortName	= new ActionItemOption(SORT_BY_NAME, getString(R.string.ascending_by_character_option_menu), getResources().getDrawable(R.drawable.menu_down_arrow));
		ActionItemOption sortTime 	= new ActionItemOption(SORT_BY_TIME, getString(R.string.ascending_by_time_option_menu), getResources().getDrawable(R.drawable.menu_up_arrow));
		ActionItemOption delete_all = new ActionItemOption(DELETE_ALL_TASK, getString(R.string.delete_all_task_option_menu),getResources().getDrawable(R.drawable.icon_delete_option));
		ActionItemOption setting = new ActionItemOption(SETTING, getString(R.string.setting_option_menu), getResources().getDrawable(R.drawable.setting_option));
		//use setSticky(true) to disable QuickAction dialog being dismissed after an item is clicked
		sortTime.setSticky(true);
		sortName.setSticky(true);
		delete_all.setSticky(true);
		setting.setSticky(true);
      //create QuickAction. Use QuickAction.VERTICAL or QuickAction.HORIZONTAL param to define layout 
        //orientation
        final QuickActionOption quickAction = new QuickActionOption(this, QuickActionOption.VERTICAL);
      //add action items into QuickAction
        quickAction.addActionItem(sortName);
		quickAction.addActionItem(sortTime);
		quickAction.addActionItem(delete_all);
		quickAction.addActionItem(setting);
		quickAction.setOnActionItemClickListener(new OnActionItemClickListener() {		
			@Override
			public void onItemClick(QuickActionOption source, int pos, int actionId) {
				ActionItemOption actionItem = quickAction.getActionItem(pos);
				switch (actionId) {
				case SORT_BY_NAME:
					showToast("sort up", 0);
					sortNameAllTask("ASC");
					quickAction.dismiss();
					break;
				case SORT_BY_TIME:
					showToast("sort down", 0);
					sortAllTaskByTime("ASC");
					quickAction.dismiss();
					break;
				case DELETE_ALL_TASK:
					deleteAll();
					quickAction.dismiss();
					break;
				case SETTING:
					TabMain.getInstance().getTabHost().setCurrentTab(1);				
					quickAction.dismiss();
					break;
				default:
					break;
				}
				
			}
		});
		//set listnener for on dismiss event, this listener will be called only if QuickAction dialog was dismissed
		//by clicking the area outside the dialog.
		quickAction.setOnDismissListener(new OnDismissListener() {			
			@Override
			public void onDismiss() {
				
			}
		});
		quickAction.show(v);
	}
	/**
	 * ListView slide left/right like Samsung contact ListView
	 */
	public void swipeListview (){
		SwipeListViewTouchListener  touchListener =
        	    new SwipeListViewTouchListener(
            	        ls,
            	        new SwipeListViewTouchListener.OnSwipeCallback() {
            	            @Override
            	            public void onSwipeLeft(ListView listView, int [] reverseSortedPositions) {
            	                  Log.i(this.getClass().getName(), "swipe left : pos="+reverseSortedPositions[0]);
            	                // TODO : YOUR CODE HERE FOR LEFT ACTION
            	            	deleteOneTask(listtask.get(reverseSortedPositions[0]));
            	            	
            	            	
            	            }

            	            @Override
            	            public void onSwipeRight(ListView listView, int [] reverseSortedPositions) {
            	                //  Log.i(ProfileMenuActivity.class.getClass().getName(), "swipe right : pos="+reverseSortedPositions[0]);
            	                // TODO : YOUR CODE HERE FOR RIGHT ACTION
            	            	deleteOneTask(listtask.get(reverseSortedPositions[0]));
            	            }
            	        },
            	        true, // example : left action = dismiss
            	        false); // example : right action without dismiss animation;
		ls.setOnTouchListener(touchListener);
        // Setting this scroll listener is required to ensure that during ListView scrolling,
        // we don't look for swipes.
        ls.setOnScrollListener(touchListener.makeScrollListener());
	}
	
	
	/**
	 *  Get context in groupActivity.Use for show dialog
	 * @return : context
	 */
	private Context getDialogContext() {
	    Context mcontext;
	    if (getParent() != null) mcontext = getParent();
	    else mcontext = this;
	    return mcontext;
	}
	// auto show soft keybroad
	public void showKeybroad (View view){
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
		
	}
	
	public boolean getbooleanPreferences(String type){
		boolean temp;
		SharedPreferences dataSetting= PreferenceManager.getDefaultSharedPreferences(this);
		temp= dataSetting.getBoolean(type, false);
		return temp;
	}
	public boolean isNetworkOnline() {
	    boolean status=false;
	    try{
	        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	        NetworkInfo netInfo = cm.getNetworkInfo(0);
	        if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
	            status= true;
	        }else {
	            netInfo = cm.getNetworkInfo(1);
	            if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
	                status= true;
	        }
	    }catch(Exception e){
	        e.printStackTrace();  
	        return false;
	    }
	    return status;

	    }  
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		ls=null;
		dateUtils=null;
		System.gc();
	}

}